package com.hourupdate.network.bean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Map;

import org.apache.log4j.Logger;

import com.hourupdate.network.connection.ConnectionJDBC;

public class RunningLock {
	static final Logger logger = Logger.getLogger(RunningLock.class);
	private static RunningLock instance;
	public static RunningLock getInstance() {
		if (instance == null) {
			instance = new RunningLock();
		}
		return instance;
	}
	/**
	 * Gets the Value
	 * @param param The param name
	 * @return Returns a String
	 */	
	public synchronized String getCdnId(String cn_id, String curent_date) throws Exception {
		String strSchema = ConnectionJDBC.schema;
		String table = ConnectionJDBC.schemaRUNNING;
		Running rn = new Running();
		Connection conn = new ConnectionJDBC().getJDBConnection();
		boolean insertSuccess = false;
		try{
			String sql = "";
			
			sql = " SELECT CDN_ID FROM "+ strSchema +"."+table+" WHERE CN_ID = ? AND CREATE_DATE = ? ORDER BY CREATE_DATE DESC";
			
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, cn_id);
			ps.setString(2, curent_date);
			
			ExecuteSQLBean eb = new ExecuteSQLBean();
			ArrayList<Map<String, String>> result = eb.executeQuery(ps);
			ps.close();
			//Lock Table
//			sql = "LOCK TABLE "+ strSchema +"."+table+" READ";
//			ex.executeStatement(conn, sql);
			
			if (result != null && result.size() > 0) {
				Map<String, String> data = result.get(0);
				Long cdn_id = Long.parseLong(data.get("CDN_ID"))+1;
				rn.setCdn_id(String.valueOf(cdn_id));
				rn.setCn_id(cn_id);
				rn.setCreate_date(curent_date);
				insertSuccess = rn.updatePreparedStatement(conn);
			}else{
				rn.setCdn_id(String.valueOf(curent_date+"001"));
				rn.setCn_id(cn_id);
				rn.setCreate_date(curent_date);
				insertSuccess = rn.insertPreparedStatement(conn);
			}
		}catch(Exception e){
			logger.error(e.getMessage());
		}finally{
			if(insertSuccess){
				conn.commit();
			}else{
				conn.rollback();
			}
			if (conn != null)conn.close();
		}
		return rn.getCdn_id();
	}
}
